package cn.akwangl.socket.aio.simple;

import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.Map;

/**
 * 处理客户端读写.
 *
 * @author 阿坤同学
 * @date 2022/6/26 17:28
 * @since 0.0.6
 */
@Slf4j
public class ClientHandler implements CompletionHandler<Integer, Object> {
    private AsynchronousSocketChannel socketChannel;

    public ClientHandler(AsynchronousSocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    @Override
    public void completed(Integer len, Object attachment) {
        Map<String, Object> map = (Map) attachment;
        String type = (String) map.get("type");
        ByteBuffer byteBuffer = (ByteBuffer) map.get("data");
        if ("read".equals(type)) {
            //  写回客户端
            map.put("type", "write");
            byteBuffer.flip();
            socketChannel.write(byteBuffer, map, this);
        } else if ("write".equals(type)) {
            byteBuffer.clear();
            map.put("type", "read");
            socketChannel.read(byteBuffer, map, this);
        }
    }

    @Override
    public void failed(Throwable exc, Object attachment) {
        log.error("client 处理失败", exc);
    }
}
